package com.siecom.hostservice;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.util.Log;

import com.google.protobuf.InvalidProtocolBufferException;
import com.siecom.framework.device.SiecomDevice;
import com.siecom.framework.device.SiecomTask;
import com.siecom.nativelibs.NativeFunction;
import com.siecom.proto.Message;
import com.siecom.tool.ByteTool;
import com.siecom.tool.LogUtil;
import com.siecom.transport.CommServer;
import com.siecom.transport.Distribution;
import com.siecom.transport.handler.ServiceHandler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class BLEperipheral extends CommServer {

    private static final String TAG = BLEperipheral.class.getSimpleName();
    private HashMap<Integer, ServiceHandler> handlerMap = Distribution.handlerMap;
    private Context context;

    private BLEperipheral (){
        return;
    }
    private BLEperipheral(Context context) {
        this.context = context;
    }

    public static final UUID UUID_SERVICE =          UUID.fromString("49535343-FE7D-4AE5-8FA9-9FAFD205E455"); //自定义UUID
    public static final UUID UUID_CHAR_READ_NOTIFY = UUID.fromString("49535343-8841-43F4-A8D4-ECBE34729BB3");
    public static final UUID UUID_DESC_NOTITY =      UUID.fromString("49535343-8841-43F4-A8D4-ECBE34729BB3");
    public static final UUID UUID_CHAR_WRITE =       UUID.fromString("49535343-1E4D-4BD9-BA61-23C647249616");

//    public static final UUID UUID_SERVICE = UUID.fromString("10000000-0000-0000-0000-000000000000"); //自定义UUID
//    public static final UUID UUID_CHAR_READ_NOTIFY = UUID.fromString("11000000-0000-0000-0000-000000000000");
//    public static final UUID UUID_DESC_NOTITY = UUID.fromString("11100000-0000-0000-0000-000000000000");
//    public static final UUID UUID_CHAR_WRITE = UUID.fromString("12000000-0000-0000-0000-000000000000");

//    public static final UUID UUID_SERVICE =          UUID.fromString("00001803-0000-1000-8000-00805f9b34fb"); //自定义UUID
//    public static final UUID UUID_CHAR_READ_NOTIFY = UUID.fromString("00002A99-0000-1000-8000-00805f9b34fb");
//    public static final UUID UUID_DESC_NOTITY =      UUID.fromString("00002A99-0000-1000-8000-00805f9b34fb");
//    public static final UUID UUID_CHAR_WRITE =       UUID.fromString("00002A06-0000-1000-8000-00805f9b34fb");


    private BluetoothLeAdvertiser mBluetoothLeAdvertiser; // BLE广播
    private BluetoothGattServer mBluetoothGattServer; // BLE服务端
    private static   BLEperipheral mBlePeripheral = null;
    private BluetoothGatt mBluetoothGatt = null;
    private  BluetoothDevice mBTDevice;
    private int mRequestId = 0;
    private int mOffset = 0;

    private static Object lock = new Object();
    public static BLEperipheral getBleInstance(Context context){
        if(mBlePeripheral == null){
            synchronized (lock){
                if (mBlePeripheral == null){
                    mBlePeripheral = new BLEperipheral(context);
                }
            }
        }
        return mBlePeripheral;
    }
    BluetoothGattCharacteristic characteristicRead;
    public void initBle() {

        // BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        LogUtil.e(TAG,"bluetoothAdapter : " + (bluetoothAdapter == null));
        // ============启动BLE蓝牙广播(广告) =================================================================================
        //广播设置(必须)
        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY) //广播模式: 低功耗,平衡,低延迟
                .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH) //发射功率级别: 极低,低,中,高
                .setConnectable(true) //能否连接,广播分为可连接广播和不可连接广播
                .build();
        //广播数据(必须，广播启动就会发送)
        AdvertiseData advertiseData = new AdvertiseData.Builder()
                .setIncludeDeviceName(true) //包含蓝牙名称
                .setIncludeTxPowerLevel(true) //包含发射功率级别
                .addManufacturerData(1, new byte[]{23, 33}) //设备厂商数据，自定义
                .build();
        //扫描响应数据(可选，当客户端扫描时才发送)
        AdvertiseData scanResponse = new AdvertiseData.Builder()
                .addManufacturerData(2, new byte[]{66, 66}) //设备厂商数据，自定义
                .addServiceUuid(new ParcelUuid(UUID_SERVICE)) //服务UUID
                //      .addServiceData(new ParcelUuid(UUID_SERVICE), new byte[]{2}) //服务数据，自定义
                .build();
//        LogUtil.e(TAG,"bluetoothAdapter.isEnabled() : " + bluetoothAdapter.isEnabled());

        assert bluetoothAdapter != null;
        mBluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
        LogUtil.e(TAG,"mBluetoothLeAdvertiser : " + (mBluetoothLeAdvertiser == null));
        mBluetoothLeAdvertiser.startAdvertising(settings, advertiseData, scanResponse, mAdvertiseCallback);

    }

    // BLE广播Callback
    private AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            Loge("BLE广播开启成功");
            addService();
        }

        @Override
        public void onStartFailure(int errorCode) {
            Loge("BLE广播开启失败,错误码:" + errorCode);
        }

    };
    public void addService(){
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        // 注意：必须要开启可连接的BLE广播，其它设备才能发现并连接BLE服务端!
        // =============启动BLE蓝牙服务端=====================================================================================
        BluetoothGattService service = new BluetoothGattService(UUID_SERVICE, BluetoothGattService.SERVICE_TYPE_PRIMARY);
        //添加可读+通知characteristic
        characteristicRead = new BluetoothGattCharacteristic(UUID_CHAR_READ_NOTIFY,
                BluetoothGattCharacteristic.PROPERTY_READ|
                        BluetoothGattCharacteristic.PROPERTY_NOTIFY
                , BluetoothGattCharacteristic.PERMISSION_READ
                | BluetoothGattCharacteristic.PERMISSION_WRITE);
        characteristicRead.addDescriptor(new BluetoothGattDescriptor(UUID_DESC_NOTITY, BluetoothGattCharacteristic.PERMISSION_WRITE));
        //添加可写characteristic
        BluetoothGattCharacteristic characteristicWrite = new BluetoothGattCharacteristic(UUID_CHAR_WRITE,
                BluetoothGattCharacteristic.PROPERTY_WRITE,
                BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PERMISSION_WRITE);
        //添加特性
        service.addCharacteristic(characteristicRead);
        service.addCharacteristic(characteristicWrite);
        if (bluetoothManager != null)
            mBluetoothGattServer = bluetoothManager.openGattServer(context, mBluetoothGattServerCallback);
        mBluetoothGattServer.addService(service);
    }

    private void Loge(String s) {
        Log.e(TAG,s);
    }
    // BLE服务端Callback
    private BluetoothGattServerCallback mBluetoothGattServerCallback = new BluetoothGattServerCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            mBTDevice = device;
            Log.i(TAG, String.format("onConnectionStateChange:name == %s/n,address ==%s/n,status ==  %s/n,newStatus == %s", device.getName(), device.getAddress(), status, newState));
            Loge(String.format(status == 0 ? (newState == 2 ? "与[%s]连接成功" : "与[%s]连接断开") : ("与[%s]连接出错,错误码:" + status), device));
            totalLen = 0;
            mByteArray.clear();
            if(status == 0 && newState == 2){
                android.os.Message message = new android.os.Message();
                message.what = MainActivity.animeStart;
                Bundle bundle = new Bundle();
                String name = device.getName() == null? "pad": device.getName();
                bundle.putString("name", name);
                bundle.putString("address", device.getAddress());
                message.setData(bundle);
                MainActivity.animehandler.sendMessageDelayed(message, 1000);

            }else {
                MainActivity.disconnectBlue();
            }

        }

        @Override
        public void onServiceAdded(int status, BluetoothGattService service) {
            Log.i(TAG, String.format("onServiceAdded:%s,%s", status, service.getUuid()));
            Loge(String.format(status == 0 ? "添加服务[%s]成功" : "添加服务[%s]失败,错误码:" + status, service.getUuid()));
        }


        @SuppressLint("MissingPermission")
        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
            Log.i(TAG, String.format("onCharacteristicReadRequest:%s,%s,%s,%s,%s", device.getName(),
                    device.getAddress(), requestId, offset, characteristic.getUuid()));


            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());// 响应客户端

            Loge("客户端读取Characteristic[" + characteristic.getUuid() + "]:\n characteristic.getValue ==" + ByteTool.byte2hex(characteristic.getValue()));

        }

        @SuppressLint("MissingPermission")
        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
                                                 BluetoothGattCharacteristic characteristic,
                                                 boolean preparedWrite, boolean responseNeeded,
                                                 int offset, byte[] requestBytes) {
            // 获取客户端发过来的数据
            String requestStr;
            requestStr = ByteTool.byte2hex(requestBytes);
            Log.e(TAG, String.format("onCharacteristicWriteRequest:%s,%s,%s,%s,%s,%s,%s,%s", device.getName(),
                    device.getAddress(), requestId, characteristic.getUuid(),
                    preparedWrite, responseNeeded, offset, requestStr));

            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, requestBytes);// 响应客户端
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            logTv("客户端写入Characteristic[" + characteristic.getUuid() + "]:\n" + requestStr);
            // todo 解析收到的数据
            receiveFromRemote(requestBytes);
//            startListen(requestBytes);
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
            Log.i(TAG, String.format("onDescriptorReadRequest:%s,%s,%s,%s,%s", device.getName(), device.getAddress(), requestId, offset, descriptor.getUuid()));
            String response = "DESC_" + (int) (Math.random() * 100); //模拟数据
            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, response.getBytes()); // 响应客户端
            Loge("客户端读取Descriptor[" + descriptor.getUuid() + "]:\n" + response);
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onDescriptorWriteRequest(final BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            // 获取客户端发过来的数据
            String valueStr = Arrays.toString(value);
            Log.i(TAG, String.format("onDescriptorWriteRequest:%s,%s,%s,%s,%s,%s,%s,%s", device.getName(), device.getAddress(), requestId, descriptor.getUuid(),
                    preparedWrite, responseNeeded, offset, valueStr));
            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);// 响应客户端
            Loge("客户端写入Descriptor[" + descriptor.getUuid() + "]:\n" + valueStr);

            // 简单模拟通知客户端Characteristic变化
//            if (Arrays.toString(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE).equals(valueStr)) { //是否开启通知
//                final BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        for (int i = 0; i < 1; i++) {
////                            SystemClock.sleep(3000);
//                            String response = "CHAR_" + (int) (Math.random() * 100); //模拟数据
//                            characteristic.setValue(response);
//                            mBluetoothGattServer.notifyCharacteristicChanged(device, characteristic, false);
//                            logTv("通知客户端改变Characteristic[" + characteristic.getUuid() + "]:\n" + response);
//                        }
//                    }
//                }).start();
//            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
            super.onExecuteWrite(device,requestId,execute);
            Log.e(TAG, String.format("onExecuteWrite:%s,%s,%s,%s", device.getName(), device.getAddress(), requestId, execute));
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onNotificationSent(BluetoothDevice device, int status) {
            super.onNotificationSent(device,status);
//            Log.e(TAG, String.format("onNotificationSent:%s,%s,%s", device.getName(), device.getAddress(), status));
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onMtuChanged(BluetoothDevice device, int mtu) {
            Log.e(TAG, String.format("onMtuChanged:%s,%s,%s", device.getName(), device.getAddress(), mtu));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    SiecomDevice.connectToBtDevice(null, new SiecomTask.TaskCallback() {
                        @Override
                        public void onStart(Bundle bundle) {

                        }

                        @Override
                        public void onSucceed(Bundle bundle) {
                            LogUtil.e(TAG,"connectToBtDevice onSucceed" );
                        }

                        @Override
                        public void onError(Bundle bundle) {
                            LogUtil.e(TAG,"connectToBtDevice onError" );
                        }
                    });
                    Looper.loop();
                }
            }).start();

        }
    };

    /**
     * 发送通知给主机
     *
     * @param device         ：发送的目标设备
     * @param characteristic ：用来通知的characteristic
     * @param data           ：通知的内容
     */
    public boolean notifyToMaster(BluetoothDevice device, BluetoothGattCharacteristic characteristic, byte[] data) {
        if (device != null && characteristic != null && data != null) {
            //设置写操作的类型 WRITE_TYPE_DEFAULT的情况选  底层会自动分包 不用人为分包
            characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            //把要设置的数据装进characteristic
            characteristic.setValue(data);
            //发送出去
            return mBluetoothGattServer.notifyCharacteristicChanged(device, characteristic, false);
        } else {
            return false;
        }

    }


    private static final int perLen = 180;
    byte[] crcOut = new byte[2];
    public static ExecutorService executorService = Executors.newSingleThreadExecutor();
    @Override
    public void sendToRemote(Message.siecomproto msg) {
        super.sendToRemote(msg);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                synchronized (this){
                    LogUtil.e(TAG,"发送数据："+ msg.toString());

                    byte[] b = msg.toByteArray();
//                        LogUtil.e(TAG,"发送数据："+ ByteTool.byte2hex(b));
                    int len = b.length;
                    int allLen = len + 5;
                    byte[] allData = new byte[allLen];
                    allData[0] = 0x02;
                    allData[1] = (byte)(len / 256);
                    allData[2] = (byte)(len % 256);
                    System.arraycopy(b,0,allData,3,len);
//                        LogUtil.e(TAG,"带头和长度："+ ByteTool.byte2hex(allData));
                    NativeFunction.Crc16CCITT2(allData,len+3,0,crcOut);
//                        LogUtil.e(TAG,"crcOut=="+ ByteTool.byte2hex(crcOut));
                    allData[len + 3] = crcOut[0];
                    allData[len + 4] = crcOut[1];
//                    LogUtil.e(TAG,"带头和长度："+ ByteTool.byte2hex(allData));
                    LogUtil.e(TAG,"总长度长度："+ allData.length);
                    int offset = 0;
                    long start = System.currentTimeMillis();
                    while (allLen > 0){


                        byte[] sendPer = new byte[perLen];
                        if(allLen >= perLen){
                            System.arraycopy(allData,offset,sendPer,0,perLen);
                        }else {
                            LogUtil.e(TAG,"剩余allLen == " + allLen);
                            sendPer = new byte[allLen];
                            System.arraycopy(allData,offset,sendPer,0,allLen);
                        }
//                        LogUtil.e(TAG,"sendPer == " + ByteTool.byte2hex(sendPer));
                        notifyToMaster(mBTDevice,characteristicRead,sendPer);
                        allLen -= perLen;
                        offset += perLen;
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    LogUtil.e(TAG,"发送耗时：" + (System.currentTimeMillis() - start));
                    totalLen = 0;
                    mByteArray.clear();
                }

            }

        };

        executorService.submit(runnable);
    }

    int totalLen = 0;
    ArrayList mByteArray = new ArrayList<Byte>();
    public static ExecutorService executorService2 = Executors.newFixedThreadPool(1);
    public void receiveFromRemote(byte[] indata){
        Runnable runnable  = new Runnable() {
            @Override
            public void run() {
                try {
                    int len = indata.length;
                    if(len > 0){
                        totalLen += len;
                        byte[] b = new byte[len];
                        LogUtil.e(TAG,"接收到的数据len：" + len + " -- totalLen = " + totalLen);
                        LogUtil.e(TAG,"b.length = " + b.length);

                        for(int j = 0; j< len;j++){
                            mByteArray.add(indata[j]);
                        }

                        LogUtil.e(TAG,"mByteArray.size = " + mByteArray.size());
                        LogUtil.e(TAG,"totalLen = " + totalLen);
                        byte[] sendByte = new byte[totalLen];
                        for(int m = 0;m < totalLen; m++){
                            sendByte[m] = (byte)mByteArray.get(m);
                        }

                        if(sendByte[0] == 0x02){
                            int sendLen = (sendByte[1]&0XFF) * 256 + (sendByte[2]&0XFF);
                            if(sendLen + 5 == totalLen){
                                byte[] bytes = new byte[sendLen];
                                System.arraycopy(sendByte,3,bytes,0,sendLen);
                                LogUtil.e(TAG,"接收到的数据byte：" + ByteTool.byte2hex(bytes));
                                com.siecom.proto.Message.siecomproto msg = Message.siecomproto.parseFrom(bytes);
                                totalLen = 0;
                                mByteArray.clear();
                                LogUtil.e(TAG,"接收到的数据msg：" + msg.toString() + "--length==" + sendByte.length);
                                int module = msg.getModule();

                                if (handlerMap.containsKey(module)) {
                                    ServiceHandler handler = handlerMap.get(module);
                                    handler.onReceive(BLEperipheral.this, msg,"");
                                }
                            }

                        }else {
                            totalLen = 0;
                            mByteArray.clear();
                        }


                    }

                } catch (InvalidProtocolBufferException ex) {
                    ex.printStackTrace();
                    LogUtil.e(TAG,"InvalidProtocolBufferException");
                    //                            totalLen = 0;
                    //                            mByteArray.clear();
                } catch (IndexOutOfBoundsException e){
                    e.printStackTrace();
                    LogUtil.e(TAG,"IndexOutOfBoundsException :" + e.getMessage());
                    totalLen = 0;
                    mByteArray.clear();
                }

            }
        };

        executorService2.submit(runnable);

    }

    public void startListen(byte[] indata){
        Observable<Message.siecomproto> observable = listen(indata);
        Observer<Message.siecomproto> observer = new Observer<Message.siecomproto>() {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
                Log.e("listen", "finish");

            }


            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable disposable) {


            }

            @SuppressLint("InvalidWakeLockTag")
            @Override
            public void onNext(Message.siecomproto msg) {

                int module = msg.getModule();
                LogUtil.e("module:", "==" + module);

                if (handlerMap.containsKey(module)) {
                    ServiceHandler handler = handlerMap.get(module);
                    handler.onReceive(BLEperipheral.this, msg,"");


                }

            }
        };

        observable.subscribe(observer);
    }
    public Observable<Message.siecomproto> listen(byte[] indata) {
        return Observable.create(new ObservableOnSubscribe<Message.siecomproto>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Message.siecomproto> observableEmitter) throws Exception {

                try {
                    int len = indata.length;
                    if(len > 0){
                        totalLen += len;
                        byte[] b = new byte[len];
                        LogUtil.e(TAG,"接收到的数据len：" + len + " -- totalLen = " + totalLen);
                        LogUtil.e(TAG,"b.length = " + b.length);

                        for(int j = 0; j< len;j++){
                            mByteArray.add(indata[j]);
                        }

                        LogUtil.e(TAG,"mByteArray.size = " + mByteArray.size());
                        LogUtil.e(TAG,"totalLen = " + totalLen);
                        byte[] sendByte = new byte[totalLen];
                        for(int m = 0;m < totalLen; m++){
                            sendByte[m] = (byte)mByteArray.get(m);
                        }

                        if(sendByte[0] == 0x02){
                            int sendLen = (sendByte[1]&0XFF) * 256 + (sendByte[2]&0XFF);
                            if(totalLen == sendLen + 5){
                                byte[] bytes = new byte[sendLen];
                                System.arraycopy(sendByte,3,bytes,0,sendLen);
                                LogUtil.e(TAG,"接收到的数据byte：" + ByteTool.byte2hex(bytes));
                                com.siecom.proto.Message.siecomproto msg = Message.siecomproto.parseFrom(bytes);
                                LogUtil.e(TAG,"接收到的数据msg：" + msg.toString() + "--length==" + sendByte.length);
                                totalLen = 0;
                                mByteArray.clear();
                                observableEmitter.onNext(msg);
                            }


//                            int module = msg.getModule();
//
//                            if (handlerMap.containsKey(module)) {
//                                ServiceHandler handler = handlerMap.get(module);
//                                handler.onReceive(BLEperipheral.this, msg,"");
//                            }
                        }else {
                            totalLen = 0;
                            mByteArray.clear();
                        }


                    }

                } catch (InvalidProtocolBufferException ex) {
                    ex.printStackTrace();
                    LogUtil.e(TAG,"InvalidProtocolBufferException");
                    //                            totalLen = 0;
                    //                            mByteArray.clear();
                } catch (IndexOutOfBoundsException e){
                    LogUtil.e(TAG,"IndexOutOfBoundsException :" + e.getMessage());
                    totalLen = 0;
                    mByteArray.clear();
                }

            }
        }).subscribeOn(Schedulers.newThread());


    }

}
